<?php
/**
 * Created by PhpStorm.
 * User: Xu_Jiarui
 * Date: 2017/8/9
 * Time: 16:22
 */
namespace user;

use think\Session;

class Auth{

    const AUTH_URL = "http://121.42.195.176:9501";

    const AUTH_MODULE = "seabook";

    const AUTH_SERVICE = "adminservice";

    public static function login($username, $password){

        if(empty($username)|| empty($password)){
            return false;
        }

        $request_data = array(
            'function' => Auth::AUTH_MODULE.'.'.Auth::AUTH_SERVICE.'.login',
            'data'=>array(
                'username'=>$username,
                'password'=>$password
            )
        );

        $request_url = Auth::AUTH_URL.'?data='.json_encode($request_data);

        $feedback = Auth::makeRequest($request_url);

        if($feedback['code']!= '200'){
            //记录请求失败日志
            return array('retCode'=>-999,'msg'=>'server error');
        }

        $result = json_decode($feedback['result'],true);

        return $result;

    }

    public static function check($token, $permissionFlag = false, $userId = '', $controller = 0, $operation = 0){

        if(empty($token)){
            return false;
        }
        if (self::isAdministrator()) {
            return array('resCode' => 2);
        }

        $request_data = array(
            'function' => Auth::AUTH_MODULE.'.'.Auth::AUTH_SERVICE.'.checkLogin',
            'data'=>array(
                'sessionId'=>$token,
                'checkPs' => $permissionFlag,
                'userId' => $userId,
                'controller' => $controller,
                'operation' => $operation
            )
        );

        $request_url = Auth::AUTH_URL.'?data='.json_encode($request_data);

        $feedback = Auth::makeRequest($request_url);

        if($feedback['code']!= '200'){
            //记录请求失败日志
            return false;
        }

        $result = json_decode($feedback['result'],true);

        return $result['data'];

    }

    public static function logout($token){

        if(empty($token)){
            return false;
        }

        $request_data = array(
            'function' => Auth::AUTH_MODULE.'.'.Auth::AUTH_SERVICE.'.loginOut',
            'data'=>array(
                'sessionId'=>$token
            )
        );

        $request_url = Auth::AUTH_URL.'?data='.json_encode($request_data);

        $feedback = Auth::makeRequest($request_url);

        if($feedback['code']!= '200'){
            //记录请求失败日志
            return false;
        }

        $result = json_decode($feedback['result'],true);

        if($result['retCode']!=2 || $result['data']['resCode']!=2){
            return false;
        }

        return true;

    }

    public static function makeRequest($url, $params = array(), $expire = 5, $extend = array(), $hostIp = '')
    {
        if (empty($url)) {
            return array('code' => '100');
        }

        $_curl = curl_init();
        $_header = array(
            'Accept-Language: zh-CN',
            'Connection: Keep-Alive',
            'Cache-Control: no-cache'
        );
        // 方便直接访问要设置host的地址
        if (!empty($hostIp)) {
            $urlInfo = parse_url($url);
            if (empty($urlInfo['host'])) {
                $urlInfo['host'] = substr(DOMAIN, 7, -1);
                $url = "http://{$hostIp}{$url}";
            } else {
                $url = str_replace($urlInfo['host'], $hostIp, $url);
            }
            $_header[] = "Host: {$urlInfo['host']}";
        }


        // 只要第二个参数传了值之后，就是POST的
        if (!empty($params)) {
            curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }

        if (substr($url, 0, 8) == 'https://') {
            curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);

        if ($expire > 0) {
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }

        // 额外的配置
        if (!empty($extend)) {
            curl_setopt_array($_curl, $extend);
        }

        $result['result'] = curl_exec($_curl);
        $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info'] = curl_getinfo($_curl);
        if ($result['result'] === false) {
            $result['result'] = curl_error($_curl);
            $result['code'] = -curl_errno($_curl);
        }

        curl_close($_curl);
        return $result;
    }

    public static function adminServiceRequest($function = '', $data = array())
    {
        $function = trim($function);
        if (empty($function)) {
            return false;
        }
        $param = array(
            'function' => Auth::AUTH_MODULE . ".{$function}",
            'data' => $data
        );
        $param = array(
            'data' => json_encode($param)
        );
        $result = Auth::makeRequest(Auth::AUTH_URL, $param);
        $result = json_decode($result['result'], true);
        return $result;
    }

    public static function isAdministrator()
    {
        if (Session::get('username') == 'administrator') {
            return true;
        } else {
            return false;
        }
    }
}